﻿/**
* 图层ID : m_listData的数组下标
* index：  m_listData中的数据ConfData，index值
*/




#include "chartoperate.h"

ChartOperate::ChartOperate(QCustomPlot *plot) :
    m_XScale(1.1)
  , m_YScale(1.1)
  , m_xMinRange(0)
  , m_xMaxRange(10)
  , m_yMinRange(0)
  , m_yMaxRange(10)
  , m_changeFlag(false)
  , m_cntLineUUID("")
  , m_cntPointIndex(-1)
  , m_cntDargIndex(-1)
  , m_dragFlag(false)
  , m_mousePos(0,0)
  , m_isUpFlag(false)
  , m_legendIsShow(true)
  , m_selectFlag(true)
{
    m_plot = plot;
    m_data = new DataOperate();
}

// 绑定图表中的Chart和
void ChartOperate::selectionChanged()
{
    if (m_plot->xAxis->selectedParts().testFlag(QCPAxis::spAxis) || m_plot->xAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
            m_plot->xAxis2->selectedParts().testFlag(QCPAxis::spAxis) || m_plot->xAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
    {
        m_plot->xAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
        m_plot->xAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
    }
    
    if (m_plot->yAxis->selectedParts().testFlag(QCPAxis::spAxis) || m_plot->yAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
            m_plot->yAxis2->selectedParts().testFlag(QCPAxis::spAxis) || m_plot->yAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
    {
        m_plot->yAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
        m_plot->yAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
    }
    
    // synchronize selection of graphs with selection of corresponding legend items:
    for (int i=0; i<m_plot->graphCount(); ++i)
    {
        setSelectChtLineStyle(i);
    }
}

void ChartOperate::mousePress(QMouseEvent* event)
{

    if (m_plot->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
        m_plot->axisRect()->setRangeDrag(m_plot->xAxis->orientation());
    else if (m_plot->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
        m_plot->axisRect()->setRangeDrag(m_plot->yAxis->orientation());
    else
        m_plot->axisRect()->setRangeDrag(Qt::Horizontal|Qt::Vertical);
    qreal x_pos = event->pos().x();
    qreal y_pos = event->pos().y();
    
    double x_val = m_plot->xAxis->pixelToCoord(x_pos);
    double y_val = m_plot->yAxis->pixelToCoord(y_pos);

    // 设置当前点按下的位置
    m_lblPos->setText(QString("(%1, %2)").arg(m_data->roundAxisValue(x_val)).arg(m_data->roundAxisValue(y_val)));

    m_cntLinePoint = QPointF(x_val, y_val);

    m_data->getPointInfoByPointValue(m_cntDragUUID,
                                     m_cntDargIndex, QPointF(x_val, y_val));

    m_dragFlag = (m_cntDragUUID != "" && m_cntDargIndex != -1 ) ? true : false;
    //      qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" << m_dragFlag <<  m_cntDragUUID << m_cntDargIndex;

}

void ChartOperate::mouseMove(QMouseEvent* event)
{


    if(m_dragFlag && m_cntDragUUID != "" && m_cntDargIndex != -1)
    {
        int x_pos = event->pos().x();
        int y_pos = event->pos().y();

        double x_val = m_plot->xAxis->pixelToCoord(x_pos);
        double y_val = m_plot->yAxis->pixelToCoord(y_pos);

        m_plot->setInteractions(QCP::iRangeZoom);

        x_val = x_val < 0 ? 0 : x_val;
        m_cntLinePoint = QPointF(x_val, y_val);
        // 设置当前点按下的位置
        m_lblPos->setText(QString("(%1, %2)").arg(m_data->roundAxisValue(x_val)).arg(m_data->roundAxisValue(y_val)));
        //        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : moooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo" ;
        modifyChartPoint(m_cntDragUUID, m_cntDargIndex, x_val, y_val);
        //          m_data->getGlobalDataInfos();
    }
    else
    {
        // 设置拖拽属性
        m_plot->setInteractions( QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
                                 QCP::iSelectLegend | QCP::iSelectPlottables);
    }
}

void ChartOperate::mouseRelease(QMouseEvent* event)
{
    Q_UNUSED(event);

    if(m_dragFlag && m_cntDragUUID != "" && m_cntDargIndex != -1)
    {
        int xValue = m_data->roundAxisValue(m_cntLinePoint.x());
        xValue = xValue < 0 ? 0 : xValue;
        int yValue = m_data->roundAxisValue(m_cntLinePoint.y());
        //        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  m_plot->selectedGraphs().size();
        if (m_plot->selectedGraphs().size() > 0)
        {
            QString strUid = m_plot->selectedGraphs().first()->property("UUID").toString();
            //            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : mRrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr" ;
            //            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  strUid << m_cntDragUUID;
            modifyChartPoint(m_cntDragUUID, m_cntDargIndex, xValue, yValue);
            //   修改数据  拖拽完成
            //        //        qDebug() << "m_cntLinePoint: " << m_cntLinePoint << xValue;

            m_data->modifyPointData(m_cntDragUUID, m_cntDargIndex, xValue, yValue);
            //        m_data->getGlobalDataInfos();
        }


        m_cntDargIndex = -1;
        m_cntDragUUID = "";
        m_cntLinePoint = QPointF(0, 0);
        m_dragFlag = false;

        // 设置拖拽属性
        //        m_plot->setInteractions( QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
        //                                 QCP::iSelectLegend | QCP::iSelectPlottables);
    }
}

void ChartOperate::mouseWheel()
{
    if (m_plot->xAxis->selectedParts().testFlag(QCPAxis::spAxis))
        m_plot->axisRect()->setRangeZoom(m_plot->xAxis->orientation());
    else if (m_plot->yAxis->selectedParts().testFlag(QCPAxis::spAxis))
        m_plot->axisRect()->setRangeZoom(m_plot->yAxis->orientation());
    else
        m_plot->axisRect()->setRangeZoom(Qt::Horizontal|Qt::Vertical);
}

void ChartOperate::contextMenuRequest(QPoint pos)
{
    m_mousePos = pos;
    QMenu *menu = new QMenu();
    menu->setAttribute(Qt::WA_DeleteOnClose);

    if (m_plot->legend->selectTest(pos, false) >= 0 && m_legendIsShow) // context menu on legend requested
    {

        menu->addAction(QStringLiteral("添加线"), this, SLOT(actionChtAddLine()));
        //        menu->addAction(QStringLiteral("插入线"), this, SLOT(midInsertChartLine()));
        if (m_plot->selectedGraphs().size() > 0)
        {
            if (m_data->getConfDataLen() > 1)
            {
                menu->addAction(QStringLiteral("向上移动"), this, SLOT(actionLegendUp()));
                menu->addAction(QStringLiteral("向下移动"), this, SLOT(actionLegendDown()));
            }
            menu->addAction(QStringLiteral("删除线"), this, SLOT(actionChtDelLine()));
            menu->addAction(QStringLiteral("修改图例名"), this, SLOT(modifyChtLegendName()));
        }
    }
    else
    {
        menu->addAction(QStringLiteral("添加线"), this, SLOT(actionChtAddLine()));
        menu->addAction(QStringLiteral("插入线"), this, SLOT(actionChtMidInsertLine()));
        if (m_plot->selectedGraphs().size() > 0)
        {
            menu->addAction(QStringLiteral("添加点"), this, SLOT(actionChtAddPt()));
            menu->addAction(QStringLiteral("删除线"), this, SLOT(actionChtDelLine()));
            menu->addAction(QStringLiteral("删除点"), this, SLOT(actionChtDelPt()));
        }

        if (m_plot->graphCount() > 0)
        {
            menu->addAction(QStringLiteral("删除所有线"), this, SLOT(removeAllGraphs()));
        }
        menu->addAction(QStringLiteral("锁定图表"), this, SLOT(actionLockCht()));
    }
    menu->popup(m_plot->mapToGlobal(pos));
}

void ChartOperate::plotPointClick(QCPAbstractPlottable* plottable,
                                  int dataIndex, QMouseEvent* event)
{
    Q_UNUSED(event);
    
    QString UUID = plottable->property("UUID").toString();
    int layerID = getLayerIDByUUID(UUID);

    int mm = getLineMidValue(UUID);
    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :ddddddd >>" <<  mm;
    if(layerID != -1)
    {
        const QCPGraphData *graphData = m_plot->graph(layerID)->data()->at(dataIndex);
        //        QPen graphPen;
        //        graphPen.setColor(COLOR_BLUE);
        //        graphPen.setWidthF(10);

        //        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  layerID << m_plot->graphCount();
        //        m_plot->graph(layerID)->setPen(graphPen);
        //        m_plot->replot();

        m_cntLineUUID = UUID;
        m_cntPointIndex = dataIndex;
        m_cntLinePoint = QPoint(graphData->key, graphData->value);
        //        qDebug() << "line__" << __LINE__ << "dataIndex:  " << dataIndex << graphData->key <<  graphData->value;
    }
    else
    {
        qDebug() << "line__" << __LINE__ << "Layer find Error!";
    }
    
    
}

void ChartOperate::legendPointClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
{
    Q_UNUSED(event);
    Q_UNUSED(legend);

    if(!m_plot->selectedGraphs().isEmpty())
    {
        QString strUid = m_plot->selectedGraphs().first()->property("UUID").toString();
        m_cntLegendItem = qobject_cast<QCPPlottableLegendItem*>(item);
        m_cntLegendUUID = strUid;
    }
}

void ChartOperate::legendPointDBClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
{

    Q_UNUSED(legend);
    Q_UNUSED(item);
    Q_UNUSED(event);

    if(!m_plot->selectedGraphs().isEmpty())
    {
        QString strUid = m_plot->selectedGraphs().first()->property("UUID").toString();
        if(m_data->getLineIndexByUUID(strUid) != -1)
        {
            int index =  m_data->getLineIndexByUUID(strUid); // index的值
            int yMaxValue = m_data->setYAxisValue(index, 1);

            m_plot->yAxis->setRange(yMaxValue - 5, yMaxValue + 5);
            //        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :yMaxValue" <<  yMaxValue;
        }
    }
}

// 添加线
void ChartOperate::actionChtAddLine()
{
    // 固定数据
    QVector<double> x, y, originalY;

    int layerID = m_data->getConfDataLen();
    int index = m_data->getAddNewLineIndex(); // 返回的是Index值

    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  index << layerID;
    if(index != -1)
    {
        QString name = m_data->getAddNewLineName(index + 1);
        QString UUID = m_data->setUUID(index, name);

        // 获取当前线的最大索引(返回的是第几条线，Y轴值用的值)
        //    int lineIndex = m_data->getConfDataLen();
        //    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  lineIndex;

        // 判断当前索引对应的Y值是否超过最大值
        bool isPassedMaxIndex = m_data->chkCntLintPassMaxIndex(index);
        addFixedVector(index, x, y, originalY);

        if(isPassedMaxIndex)
        {
            clearChart();

            // 修改数据
            m_data->addLineData(index, name, x, originalY);

            m_yMaxRange = m_data->getYAxisMaxValue();
            //        m_plot->yAxis->setRange(m_yMinRange,m_yMaxRange);

            reRenderChart(m_listConfData);
        }
        else
        {
            // 绘制图形
            addChartLine(layerID, UUID, name, x, y);

            // 保存数据
            m_data->addLineData(index, name, x, originalY);
        }
    }


}

// 添加点
void ChartOperate::actionChtAddPt()
{
    addChartPoint();
}

// 删除线
void ChartOperate::actionChtDelLine()
{
    //    delChartLine();
    if (m_plot->selectedGraphs().size() > 0)
    {
        QString UUID = m_plot->selectedGraphs().first()->property("UUID").toString();
        m_plot->removeGraph(m_plot->selectedGraphs().first());
        m_plot->replot();
        delApointLayerID(UUID);

        // 删除线数据
        m_data->delLineData(UUID);
    }
}

// 删除点
void ChartOperate::actionChtDelPt()
{
    delChartPoint(m_cntLinePoint.x());
}


void ChartOperate::removeAllGraphs()
{
    clearChart();
    m_data->clearAllData();
    m_yMinRange = 0;
    m_yMaxRange = 10;
}

void ChartOperate::actionLegendUp()
{
    if (m_plot->selectedGraphs().size() > 0)
    {
        // 绘图
        QString UUID = m_plot->selectedGraphs().first()->property("UUID").toString();

        clearChart();
        m_data->moveUpLine(m_listConfData, UUID);
        //        m_data->getCntConfDataValue(m_listConfData);
        reRenderChart(m_listConfData);
        m_data->getGlobalDataInfos();
    }
}

void ChartOperate::actionLegendDown()
{
    if (m_plot->selectedGraphs().size() > 0)
    {
        // 绘图
        QString UUID = m_plot->selectedGraphs().first()->property("UUID").toString();
        clearChart();
        m_data->moveDownLine(m_listConfData, UUID);
        //        m_data->getCntConfDataValue(m_listConfData);
        reRenderChart(m_listConfData);
        m_data->getGlobalDataInfos();
    }
}

void ChartOperate::actionChtMidInsertLine()
{

    // 插入线
    int posIndex = -1;

    // 判断此区域是否存在线。存在不能添加，不存在可以添加
    double y_val = m_plot->yAxis->pixelToCoord(m_mousePos.y());

    // 判断是否在有效范围，并且返回有限范围的点的y轴值
    bool isValidRange = m_data->chkCntYIsValidRange(y_val, posIndex);
    if(isValidRange)
    {
        bool nowRangeIsExist = m_data->chkNowRangeIsExist(posIndex);
        if(!nowRangeIsExist)
        {
            // 不存在，添加线
            // 固定数据
            QVector<double> x, y, originalY;
            QString name = QString("line%1").arg(posIndex);

            // 添加固定点
            addFixedVector(posIndex, x, y, originalY);
            clearChart();

            // 修改数据
            m_data->addLineData(posIndex, name, x, originalY);
            m_yMaxRange = m_data->getYAxisMaxValue();
            reRenderChart(m_listConfData);

            //            setSelectChtLineStyle(posIndex);
        }
        else
        {
            // 存在，是否替换
            //            int ret = QMessageBox::warning(this,"Title","Content");
            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : << replace" << posIndex;

        }
    }
    else
    {
        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : do not paint";
    }
}

void ChartOperate::modifyChtLegendName()
{
    if (m_cntLegendItem)
    {
        bool ok;
        QString newName = QInputDialog::getText(m_plot, QStringLiteral("修改提示"),
                                                QStringLiteral("新图例名称:"),
                                                QLineEdit::Normal,
                                                m_cntLegendItem->plottable()->name(), &ok);
        if (ok)
        {
            m_cntLegendItem->plottable()->setName(newName);
            m_plot->replot();
            m_data->modidyConfLegendByUUID(m_cntLegendUUID, newName);
        }
    }
}

void ChartOperate::makeInitChart()
{
    setChartTitle("XX chart show");
    initChartProperty();
    setChartAxis();
    initSignals();
    
}

void ChartOperate::initChartProperty()
{
    // 设置拖拽属性
    m_plot->setInteractions( QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
                             QCP::iSelectLegend | QCP::iSelectPlottables);
    // 设置legend选中后字体等
    m_plot->legend->setVisible(true);
    m_plot->rescaleAxes(true);
    
    QFont legendFont("sans", 17, QFont::Bold);
    legendFont.setPointSize(10);
    m_plot->legend->setFont(legendFont);
    m_plot->legend->setSelectedFont(legendFont);
    m_plot->legend->setSelectableParts(QCPLegend::spItems);

    //    m_plot->yAxis->setRangeLower(0);

    //    m_plot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignLeft|Qt::AlignTop);
    //    m_plot->legend->setMargins(QMargins(100,500, 0, 100));
    //    m_plot->legend->setBorderPen(Qt::NoPen);
    //    m_plot->plotLayout()->insertRow(1);


    //    m_plot->legend->addElement(0,1,m_plot->legend->item(2));
    //    m_plot->legend->addElement(0,2,m_plot->legend->item(3));

    //    m_plot->legend->addElement(1,0,m_plot->legend->item(1));
    //    m_plot->legend->addElement(1,2,m_plot->legend->item(4));

    //    m_plot->plotLayout()->addElement(1 , 0, m_plot->legend);
    //    m_plot->plotLayout()->setRowStretchFactor(1, 0.001);

}

void ChartOperate::initSignals()
{
    m_plot->setContextMenuPolicy(Qt::CustomContextMenu);
    
    connect(m_plot, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress(QMouseEvent*)));
    connect(m_plot, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMove(QMouseEvent*)));
    connect(m_plot, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseRelease(QMouseEvent*)));
    
    connect(m_plot, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
    connect(m_plot, SIGNAL(mouseWheel(QWheelEvent*)), this, SLOT(mouseWheel()));
    connect(m_plot, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(contextMenuRequest(QPoint)));
    connect(m_plot, SIGNAL(plottableClick(QCPAbstractPlottable*, int, QMouseEvent*)),
            this, SLOT(plotPointClick(QCPAbstractPlottable*, int, QMouseEvent*)));
    connect(m_plot, SIGNAL(legendClick(QCPLegend *, QCPAbstractLegendItem *, QMouseEvent *)),
            this, SLOT(legendPointClick(QCPLegend *, QCPAbstractLegendItem *, QMouseEvent *)));
    connect(m_plot, SIGNAL(legendDoubleClick(QCPLegend *, QCPAbstractLegendItem *, QMouseEvent *)),
            this, SLOT(legendPointDBClick(QCPLegend *, QCPAbstractLegendItem *, QMouseEvent *)));
}


// 初始化添加线
void ChartOperate::getInitDataAndAddLine()
{
    m_listConfData = m_data->initChartData();
    m_yMaxRange = m_data->getYAxisMaxValue();
    reRenderChart(m_listConfData);
}


void ChartOperate::setChartTitle(QString text)
{
    // 在顶部添加一行设置标题
    m_plot->plotLayout()->insertRow(0);
    QCPTextElement *title = new QCPTextElement(m_plot, text, QFont("sans", 17, QFont::Bold));
    m_plot->plotLayout()->addElement(0, 0, title);
    
    
    
}

void ChartOperate::setChartAxis()
{
    
    // 坐标轴管理
    //    m_plot->graph()->rescaleAxes(true);//坐标轴自适应
    
    m_plot->xAxis->scaleRange(m_XScale, m_plot->xAxis->range().center());
    m_plot->yAxis->scaleRange(m_YScale, m_plot->yAxis->range().center());
    
    // 坐标轴范围
    m_plot->xAxis->setRange(m_xMinRange, m_xMaxRange, Qt::AlignLeft);
    m_plot->yAxis->setRange(m_yMinRange,m_yMaxRange);
    
    m_plot->xAxis->setLabel(QStringLiteral("时间"));
    m_plot->xAxis->setLabelColor(QColor(Qt::darkCyan));
    m_plot->xAxis->setLabelFont(QFont("宋体", 12, 500, false));
    
    // 设置轴标签颜色
    m_plot->xAxis->setTickLabelColor(QColor(Qt::black));
    m_plot->xAxis->setTickLabelFont(QFont("楷体", 12, 50, false));
    m_plot->xAxis->setTickLabelRotation(-45); // 设置角度
    
    // 轴标签选中
    //    m_plot->xAxis->setSelectableParts(QCPAxis::spAxis); // 设置那部分可以选中
    //    m_plot->xAxis->setSelectedLabelColor(QColor(Qt::darkCyan));
    //    m_plot->xAxis->setSelectedTickLabelColor(QColor(Qt::darkCyan));
    //    m_plot->xAxis->setTickLength(0, 4); // 设置刻度的高
    
    m_plot->xAxis->setSubTicks(false);  // 设置子刻度不显示
    m_plot->yAxis->setSubTicks(false);  // 设置子刻度不显示
    
    m_plot->xAxis->ticker()->setTickCount(10);
    m_plot->yAxis->ticker()->setTickCount(10);
    m_plot->xAxis->ticker()->setTickOrigin(20);
    
    
    //    QSharedPointer<QCPAxisTickerFixed> ticker = QSharedPointer<QCPAxisTickerFixed>(new QCPAxisTickerFixed);
    //    ticker->setTickStepStrategy( QCPAxisTicker::tssReadability);
    //    ticker->setTickCount(200);
    //    ticker->setTickStep(1);
    //    m_plot->xAxis->setTicker(ticker);
    
    
    //    QSharedPointer<QCPAxisTickerFixed > fixTicker(new QCPAxisTickerFixed);
    //    m_plot->xAxis->setTicker(fixTicker);
}

void ChartOperate::addChartLine(int layerID, QString uuid, QString name,
                                QVector<double> pointXList, QVector<double> pointYList)
{
    m_plot->addGraph();
    m_plot->graph()->setName(name);
    m_UUIDAndID.append(uuid);  // 设置UUID与id的对应关系
    m_plot->graph()->setProperty("UUID", uuid);
    m_plot->graph()->setProperty("LAYID", layerID);
    m_plot->graph()->setLineStyle(QCPGraph::lsLine);
    m_plot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 8));
    
    QPen graphPen;
    //    graphPen.setColor(QColor(rand()%245+10, rand()%245+10, rand()%245+10));
    graphPen.setColor(COLOR_CYAN);
    graphPen.setWidthF(2);
    m_plot->graph()->setPen(graphPen);
    m_plot->graph()->setData(pointXList, pointYList);
    m_plot->replot();
}



void ChartOperate::modifyChartLine()
{
    // 修改序列名称
}

void ChartOperate::delChartLine()
{
    if (m_plot->selectedGraphs().size() > 0)
    {
        QString UUID = m_plot->selectedGraphs().first()->property("UUID").toString();
        clearChart();
        // 删除线数据
        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  UUID;
        m_data->delLineData(UUID);
        m_yMaxRange = m_data->getYAxisMaxValue();

        reRenderChart(m_listConfData);
    }
}

void ChartOperate::addChartPoint()
{
    if (m_plot->selectedGraphs().size() > 0)
    {
        double xValue = getCntLineMaxXAxis() + 1;
        double yValue = DEFAULT_YVALUE;
        
        // 绘图
        //        int layerID = m_plot->selectedGraphs().first()->property("LAYID").toInt();
        QString UUID = m_plot->selectedGraphs().first()->property("UUID").toString();
        int index = m_data->getIndexByUUID(UUID);

        chkCntPointXAxis(xValue);
        yValue = m_data->setYAxisValue(index, yValue);
        m_plot->selectedGraphs().first()->addData(xValue ,yValue);
        m_plot->replot();
        
        // 添加点数据,在最后添加，数据加1
        m_data->addPointData(UUID, xValue, DEFAULT_YVALUE);
    }
}


// 修改点
void ChartOperate::modifyChartPoint(QString UUID, int pointIndex, double xValue, double yValue)
{
    // 获取前一个点、获取后一个点
    // 修改： UUID, pointIndex, 点数据
    //    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :"
    //             <<  UUID << pointIndex << m_plot->selectedGraphs().size();
    if (m_plot->selectedGraphs().size() > 0)
    {
        QVector<double> x, y;
        // 修改图表
        //        int layerID = m_plot->selectedGraphs().first()->property("LAYID").toInt();
        QString strUid = m_plot->selectedGraphs().first()->property("UUID").toString();
        if(strUid == UUID)
        {
            //            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  yValue;
            m_data->mapDataToVector(UUID, pointIndex, x, y, xValue, yValue);

            //            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :"
            //                     <<  y;
            m_plot->selectedGraphs().first()->setData(x ,y);
            m_plot->replot();
        }

    }
}

void ChartOperate::delChartPoint(double sortKey)
{
    if (m_plot->selectedGraphs().size() > 0)
    {
        QString UUID = m_plot->selectedGraphs().first()->property("UUID").toString();

        if(m_plot->selectedGraphs().first()->data()->size() > 1)
        {
            // 删除点
            m_plot->selectedGraphs().first()->data()->remove(sortKey);
            
            // 删除点数据
            m_data->delPointData(UUID, m_cntPointIndex);
            
        }
        else
        {
            // 删除线
            m_plot->removeGraph(m_plot->selectedGraphs().first());
            delApointLayerID(UUID);

            // 删除线数据
            m_data->delLineData(UUID);
        }
        m_plot->replot();
    }
}

void ChartOperate::delAllChart()
{
    // 清空图表
    m_plot->clearGraphs();
    m_plot->replot();
    
    // 清空数据
    m_data->clearAllData();
}

void ChartOperate::actionLockCht()
{
    // 设置拖拽属性
    m_plot->setInteractions(QCP::iRangeZoom);
    m_plot->replot();
    //    m_plot->setInteractions( QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
    //                             QCP::iSelectLegend | QCP::iSelectPlottables);
}

void ChartOperate::selectTextChanged(int index)
{

    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : sssssssssssssssssssssssssssssssssssssss" ;
    QString oldFileName = m_saveEdit->text();
    QString fileName = m_cboxFiles->currentText();

    if(!fileName.isEmpty())
    {
        m_saveEdit->setText(fileName);
        m_lastFileName = fileName;
        m_lastCntIndex = m_cboxFiles->currentIndex();

        saveAnOtherFile(setIntactFilePath(oldFileName));
        openANewFile(setIntactFilePath(fileName));
    }
    else
    {
        qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : select empty" ;
    }

}

void ChartOperate::saveBtnSlot()
{

    setSaveOtherFile();




}


void ChartOperate::addSeriesText()
{
    QCPItemText *phaseTracerText = new QCPItemText(m_plot);//构造一个文本
    phaseTracerText->position->setType(QCPItemPosition::ptAxisRectRatio);//设置文本坐标解析方式，前文中有提到QCPItemPosition类的PositionType枚举
    phaseTracerText->setPositionAlignment(Qt::AlignRight | Qt::AlignBottom);//设置位置在矩形区域的位置
    phaseTracerText->position->setCoords(1.0, 0.95); // 设置位置，注意第三行代码的枚举类型和这儿的值解析方式有关系
    phaseTracerText->setText("Points of fixed\nphase define\nphase velocity vp");//文本描述
    phaseTracerText->setTextAlignment(Qt::AlignLeft);//设置文本在矩形区域的位置
    phaseTracerText->setFont(QFont("宋体", 9));//设置文本的字体
    phaseTracerText->setPadding(QMargins(8, 0, 0, 0));//设置文本所在矩形的margins
}

void ChartOperate::delApointLayerID(QString UUID)
{
    for(int i = 0; i < m_UUIDAndID.length(); ++i)
    {
        if(m_UUIDAndID.at(i) == UUID)
        {
            m_UUIDAndID.removeAt(i);
        }
    }
}

// 获取指定层，成功：返回指定层ID,失败：-1
int ChartOperate::getLayerIDByUUID(QString UUID)
{

    for(int i = 0; i < m_UUIDAndID.length(); ++i)
    {
        if(m_UUIDAndID.at(i) == UUID)
        {
            return i;
        }
    }
    return -1;
}

void ChartOperate::chkCntPointXAxis(int cntXValue)
{
    int diffValue = cntXValue - m_xMaxRange + 1;
    //    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" << m_xMaxRange;
    if(cntXValue >= m_xMaxRange)
    {
        m_xMaxRange = cntXValue + 1;
        m_xMinRange = m_xMinRange + diffValue;

        m_plot->xAxis->setRange(m_xMinRange,m_xMaxRange);
    }
    else
    {

        //        m_xMaxRange = 10;
        //        m_xMinRange = 0;

        //        m_plot->xAxis->setRange(m_xMinRange,m_xMaxRange);
    }
}

// 获取当前线的最大横坐标
int ChartOperate::getCntLineMaxXAxis()
{
    if (m_plot->selectedGraphs().size() > 0)
    {
        QSharedPointer< QCPGraphDataContainer > graphsData =  m_plot->selectedGraphs().first()->data();
        graphsData->sort();
        return graphsData->at(graphsData->size() - 1)->key;
    }
    
    return -1;
}

void ChartOperate::addFixedVector(int lineIndex, QVector<double> &x, QVector<double> &y, QVector<double> &originalY)
{
    int fixeYValue = m_data->setYAxisValue(lineIndex, 1);
    x << 0 << 1;
    y << fixeYValue << fixeYValue;
    originalY << 1 << 1;
}

void ChartOperate::clearChart()
{
    // 清空图表
    m_UUIDAndID.clear();
    m_plot->clearGraphs();
    m_plot->replot();
    m_isUpFlag = false;
}

void ChartOperate::reRenderChart(QList<ConfData> listConfData)
{
    m_data->getCntConfDataValue(listConfData);

    for(int i = 0; i < listConfData.length(); ++i)
    {
        ConfData confData = listConfData.at(i);
        QVector<double> x, y;
        QString UUID;
        int index = m_data->isUpFlagValue(confData.index, i);

        m_data->mapDataToVector(index, confData.point, x, y);
        UUID = m_data->setUUID(confData.index, confData.name);
        addChartLine(i, UUID, confData.name, x, y);
    }
}

void ChartOperate::openANewFile(QString fileName)
{
    // 获取打开文件数据，先清空图表，再用新数据渲染图表

    clearChart();
    m_data->clearAllData();
    m_data->getIniConfData(fileName);

    //    m_data->getCntConfDataValue(m_listConfData);
    reRenderChart(m_listConfData);

}

void ChartOperate::saveCntDataToFile()
{
    m_data->setSaveFileName(INI_PATH);
    m_data->saveChangedConfData();
}

bool ChartOperate::modifyFileName(QString fileName)
{
    //    QFile fileTemp(fileName);
    //    bool rmOk = fileTemp.remove();
    //    if(rmOk)
    //    {

    //    }
    //    else
    //    {
    return false;
    //    }
}

void ChartOperate::saveAnOtherFile(QString fileName)
{

    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  fileName;
    m_data->saveAnOtherDataFile(fileName);
}

void ChartOperate::isShowLegend(bool isShow)
{
    m_legendIsShow = isShow;

    //    qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  isShow;
    m_plot->legend->setVisible(isShow);
    m_plot->replot();
}

void ChartOperate::setLabelPos(QLabel *label)
{
    m_lblPos = new QLabel();
    m_lblPos = label;
}

void ChartOperate::setSelectChtLineStyle(int sceneIndex)
{
    QCPGraph *graph = m_plot->graph(sceneIndex);
    QCPPlottableLegendItem *item = m_plot->legend->itemWithPlottable(graph);

    if (item->selected() || graph->selected())
    {
        item->setSelected(true);

        QPen pen;
        pen.setWidth(3);
        pen.setColor(COLOR_BLUE);
        graph->selectionDecorator()->setPen(pen);

        graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
    }
}

QString ChartOperate::setIntactFilePath(QString fileName)
{
    return INI_DIR + fileName + ".ini";
}

void ChartOperate::reloadSelect(QString cntName)
{
    int cntIndex = 0;

    m_cBoxFileNames = m_data->getCBoxFilesData();

    for(int i = 0; i < m_cBoxFileNames.length(); ++i)
    {
        if(m_cBoxFileNames.at(i) == cntName)
        {
            cntIndex = i;
        }
    }

    if(!m_cBoxFileNames.isEmpty())
    {
        m_cboxFiles->disconnect();
        m_cboxFiles->clear();
        m_cboxFiles->addItems(m_cBoxFileNames);
        m_cboxFiles->setCurrentIndex(cntIndex);
        connect(m_cboxFiles, SIGNAL(currentIndexChanged(int)), this, SLOT(selectTextChanged(int)));

    }
}

void ChartOperate::setCBoxFiles(QComboBox *cboxFiles)
{
    m_cboxFiles = new QComboBox();
    m_cboxFiles = cboxFiles;
    setCBoxInitSetting();


    connect(m_cboxFiles, SIGNAL(currentIndexChanged(int)), this, SLOT(selectTextChanged(int)));
}


void ChartOperate::setCBoxInitSetting()
{


    m_cBoxFileNames = m_data->getCBoxFilesData();

    if(!m_cBoxFileNames.isEmpty())
    {
        QString firstFileName = m_cBoxFileNames.at(0);
        m_cboxFiles->clear();
        m_cboxFiles->addItems(m_cBoxFileNames);
        m_saveEdit->setText(firstFileName);
        m_lastFileName = firstFileName;
        m_lastCntIndex = 0;

        m_data->getIniConfData(setIntactFilePath(firstFileName));
        m_listConfData = m_data->getListConfData();
        m_yMaxRange = m_data->getYAxisMaxValue();
        reRenderChart(m_listConfData);
    }

}



void ChartOperate::setSaveTextEdit(QLineEdit *saveEdit)
{
    m_saveEdit = new QLineEdit();
    m_saveEdit = saveEdit;
}

void ChartOperate::setSaveButton(QPushButton *saveBtn)
{
    m_saveBtn = new QPushButton();
    m_saveBtn = saveBtn;

    connect(saveBtn, &QPushButton::clicked, this, &ChartOperate::saveBtnSlot);

}

int ChartOperate::getLineMidValue(QString UUID)
{

    return m_data->getLineMidValue(UUID);
}

QMap<QString, int> ChartOperate::getAllLineMidValue()
{
    return m_data->getAllLineMidValue();
}

void ChartOperate::setSaveOtherFile()
{
    if(m_saveEdit->text().isEmpty())
    {
        QMessageBox::warning(NULL, QStringLiteral("提示"), QStringLiteral("请输入保存的文件名!"),
                             QMessageBox::NoButton, QMessageBox::Yes);
    }
    else
    {
        QString filePath = setIntactFilePath(m_saveEdit->text());
        if(m_data->checkFileIsExist(filePath))
        {
            QMessageBox::warning(NULL, QStringLiteral("提示"), QStringLiteral("当前文件名文件已存在!"),
                                 QMessageBox::NoButton, QMessageBox::Yes);
        }
        else
        {
            saveAnOtherFile(filePath);
            m_lastFileName = m_saveEdit->text();

            // 修改文件重新设置下拉的值
            reloadSelect(m_lastFileName);
            QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("文件保存成功!"),
                                 QMessageBox::NoButton, QMessageBox::Yes);

        }

    }
}

void ChartOperate::setSaveNowFile()
{
    if(m_cBoxFileNames.isEmpty())
    {
        if(!m_saveEdit->text().isEmpty())
        {
            QString filePath = setIntactFilePath(m_saveEdit->text());
            saveAnOtherFile(filePath);
            m_lastFileName = m_saveEdit->text();
            // 修改文件重新设置下拉的值
            reloadSelect(m_lastFileName);
        }
        else
        {
            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : please input save filename!";
        }
    }
    else
    {
        if(!m_saveEdit->text().isEmpty())
        {
            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] :" <<  m_saveEdit->text();
            QString filePath = setIntactFilePath(m_saveEdit->text());
            QString oldPath = setIntactFilePath(m_lastFileName);


            if(m_data->delFileInfos(oldPath))
            {
                saveAnOtherFile(filePath);
                m_lastFileName = m_saveEdit->text();

                // 修改文件重新设置下拉的值
                reloadSelect(m_lastFileName);
            }
            else
            {
                qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : modify is fail!";
            }
        }
        else
        {
            qDebug() << "[" << __FUNCTION__ <<__LINE__ << "] : please input save filename!";
        }
    }
}

















